package com.xyzwps.harbor.service;

import com.xyzwps.harbor.model.VcodeScope;
import com.xyzwps.harbor.repo.VcodeScopeRepository;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import static com.xyzwps.harbor.util.HarborException.*;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class VcodeService {

    @Autowired
    private VcodeScopeRepository vcodeScopeRepository;

    public Mono<Void> validateVcode(String vcode, String scope) {
        return vcodeScopeRepository.findById(scope)
                .switchIfEmpty(Mono.error(badRequestEx("Invalid vc0de." )))
                .flatMap(vcodeScope -> {
                    if (!vcodeScope.getVcode().equals(vcode)) {
                        return Mono.error(badRequestEx("Invalid vcode." ));
                    } else if (vcodeScope.getCreateTime().isBefore(LocalDateTime.now().minusMinutes(30))) {
                        return Mono.error(badRequestEx("Vcode expired." ));
                    } else {
                        return Mono.empty();
                    }
                });
    }

    public Mono<VcodeScope> generateVcodeScope() {
        var vcodeScope = new VcodeScope();
        vcodeScope.setScope(UUID.randomUUID().toString());
        vcodeScope.setVcode(randomVcode());
        vcodeScope.setCreateTime(LocalDateTime.now());
        return vcodeScopeRepository.insert(vcodeScope).then(Mono.just(vcodeScope));
    }

    private String randomVcode() {
        return RandomStringUtils.randomNumeric(6);
    }
}